package com.kd.kdaicodemother.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.kd.kdaicodemother.exception.ErrorCode;
import com.kd.kdaicodemother.exception.ThrowUtils;
import com.kd.kdaicodemother.manager.CosManager;
import com.kd.kdaicodemother.service.ScreenshotService;
import com.kd.kdaicodemother.utils.WebScreenshotUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
@Slf4j
@Service
public class ScreenshotServiceImpl implements ScreenshotService {
    @Resource
    private CosManager cosManager;
    @Override
    public String generateAndUploadScreenshot(String webUrl) {
        //参数校验
        ThrowUtils.throwIf(StrUtil.isBlank(webUrl), ErrorCode.PARAMS_ERROR,"截图的网路地址不能为空");
        log.info("开始生成网页截图，URL：{}",webUrl);
        //本地截图
        String localScreenshotPath = WebScreenshotUtils.saveWebPageScreenshot(webUrl);
        ThrowUtils.throwIf(StrUtil.isBlank(localScreenshotPath), ErrorCode.OPERATION_ERROR,"网页截图失败");
        log.info("网页截图成功，本地路径：{}",localScreenshotPath);
        //上传截图到COS
        try {
            String cosUrl = uploadFileTOCos(localScreenshotPath);
            ThrowUtils.throwIf(StrUtil.isBlank(cosUrl), ErrorCode.OPERATION_ERROR,"上传截图到COS失败");
            log.info("上传截图到COS成功，COS URL：{}",cosUrl);
            return cosUrl;
        }finally {
            //清理本地文件
            clearLocalScreenshotFile(localScreenshotPath);
            log.info("清理本地文件成功，本地路径：{}",localScreenshotPath);
        }
    }

    /**
     * 上传截图到对象存储
     *
     * @param localScreenshotPath
     * @return 对象存储访问URL,失败返回null
     */
    private String uploadFileTOCos(String localScreenshotPath) {
        if (StrUtil.isBlank(localScreenshotPath)){
            return null;
        }
        File screenshotFile = new File(localScreenshotPath);
        if (!screenshotFile.exists()){
            return null;
        }
        //生成 COS 对象键
        String fileName = UUID.randomUUID().toString().substring(0,8) + "_compressed.jpg";
        String cosKey = generateScreenshotKey(fileName);
        return cosManager.uploadFile(cosKey, screenshotFile);
    }

    /**
     * 生成截图的对象存储键
     * @param fileName
     * @return 格式：/screenshot/2023/11/11/fileName.jpg
     */
    private String generateScreenshotKey(String fileName) {
        String datePath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        return String.format("/screenshot/%s/%s", datePath, fileName);
    }

    private void clearLocalScreenshotFile(String localScreenshotPath){
        //TODO
        File file = new File(localScreenshotPath);
        if(file.exists()){
            FileUtil.del(file);
            log.info("清理本地文件成功:{}",localScreenshotPath);
        }
    }
}
